package com.abhimanyu.bootstrap.processors;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;

import com.abhimanyu.bootstrap.enums.BootstrapConstants;
import com.abhimanyu.bootstrap.util.JobContext;
import com.abhimanyu.dataaccess.model.User;
import com.abhimanyu.messaging.model.IMessage;
import com.abhimanyu.messaging.model.TextMessage;

@Component
public class MessageTransformProcessor implements ItemProcessor<User, IMessage> {
	Logger logger = Logger.getLogger(getClass());

	@SuppressWarnings("unchecked")
	public IMessage process(User user) throws Exception {
		List<String> dollarRates = (List<String>) JobContext.getInstance().get(
				BootstrapConstants.DOLLAR_RATES);
		logger.debug(dollarRates);
		String dollarRateMessage = constructMessageText(dollarRates);
		IMessage message = transformToMessage(user, dollarRateMessage);
		return message;
	}

	private String constructMessageText(List<String> rates) {
		StringBuffer sb = new StringBuffer();
		String messageText = null;
		sb.append("Dollar rate today is");
		for (String rate : rates) {
			sb.append("\n- ").append(rate);
		}

		sb.append("\n- Service by Abhimanyu's Daily Dollar Rate Notifier.");
		messageText = sb.toString();
		return messageText;
	}

	private IMessage transformToMessage(User user, String messageText) {
		List<IMessage> messagesList = new ArrayList<IMessage>();
		TextMessage message = null;

		message = new TextMessage();
		message.setScheduledAt(user.getScheduledAt());
		message.setPhoneNumber(user.getMobileNumber());
		message.setMessageText(messageText);
		messagesList.add(message);

		return message;
	}
}
